﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.DirectoryServices;
using System.Reflection;
using System.Xml;
using System.Configuration;

using ScintillaNet;

using Plugins.Interfaces;


// An umanaged function that retrieves the states of each key

namespace PPad
{
    public partial class PPadMain : Form
    {        
        // List of plugins (we'll add every plugin loaded into this list)
        List<IPlugin> Plugins = new List<IPlugin>();

        // A list of documents, every open document is here
        List<Doc> Documents = new List<Doc>();


        

        string fileDialogFilter = "All files (*.*)|*.*|Plain text(*.txt)|*.txt|C# source code(*.cs)|*.cs|Extensible Markup Language(*.xml)|*.xml";

        public PPadMain()
        {
            InitializeComponent();
        }

        
        private void Form1_Load(object sender, EventArgs e)
        {
            this.WindowState = (FormWindowState)FromString(ConfigurationSettings.AppSettings["WindowState"], typeof(FormWindowState));
            if (Control.IsKeyLocked(Keys.CapsLock))
                toolStripStatusLabel1.Text = "CAPS";
            else
                toolStripStatusLabel1.Text = "";

            Doc newDocument = NewDoc();
            Documents.Add(newDocument);
            Documents[Documents.Count - 1].Text = "Document " + (Documents.Count - 1).ToString();
            
            // Load plugins
            loadPlugins();
        }

        // Convert a string to an object

        object FromString(object obj, Type type)
        {
            TypeConverter converter = TypeDescriptor.GetConverter(type);
            return converter.ConvertFromString(obj.ToString());
        }


        // loadPlugins
        private void loadPlugins()
        {
            // Loop trough each file in "plugins" folder
            foreach (string Filename in Directory.GetFiles(Path.Combine(Application.StartupPath, "plugins"), "*.dll"))
            {
                Assembly asm = Assembly.LoadFile(Filename);
                foreach (Type asmType in asm.GetTypes())
                {
                    if (asmType.GetInterface("IPlugin") != null)
                    {
                        IPlugin plugin = (IPlugin)Activator.CreateInstance(asmType);

                        // Check if plugin must be run at load
                        if (plugin.Autorun == true)
                        {
                            plugin.Run(this);
                        }
                        // Add plugin to list
                        Plugins.Add(plugin);
                    }
                }
            }

            // Create a menu item for plugins
            ToolStripMenuItem mitem = new ToolStripMenuItem();
            mitem.Text = "Plugins";

            // Now insert every loaded plugin's name in menu "Plugins"
            foreach (IPlugin plugin in Plugins)
            {
                if (plugin.ShowInMenu)
                {
                    ToolStripMenuItem subitem = new ToolStripMenuItem();
                    subitem.Click += new EventHandler(pluginsEventHandler);
                    subitem.Text = plugin.Name;

                    mitem.DropDownItems.Add(subitem);
                }
            }
            // Insert the menu item "Plugins". before the last menu item.
            mainMenu.Items.Insert((mainMenu.Items.Count - 1), mitem);
        }

        // Event handler of plugins menu items
        void pluginsEventHandler(object sender, EventArgs e)
        {
            foreach (IPlugin plugin in Plugins)
            {
                if (plugin.Name == sender.ToString())
                {
                    plugin.Run(this);
                }
            }
        }

        // Just for getting status of CAPS LOCK key
        private void PPadMain_KeyUp(object sender, KeyEventArgs e)
        {
            if (Control.IsKeyLocked(Keys.CapsLock))
            {
                toolStripStatusLabel1.Text = "CAPS";
            }
            else
            {
                toolStripStatusLabel1.Text = "";
            }
        }

        // ...
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            newFileMenuItem_Click(sender, e);
        }

        // Show preferences
        private void preferencesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Doc newDocument;
            string fileName = Application.StartupPath + "\\..\\..\\app.config"; 
            newDocument = NewDoc(fileName);
        }

        // New document
        private Doc NewDoc()
        {
            Doc newDocument = new Doc();
            
            newDocument.newDocWidth = (int)FromString(ConfigurationSettings.AppSettings["documentDefaultWidth"], typeof(int));
            newDocument.newDocHeight = (int)FromString(ConfigurationSettings.AppSettings["documentDefaultHeight"], typeof(int));
            newDocument.newDocBackgroundColor = ConfigurationSettings.AppSettings["backgroundColor"];
            newDocument.newDocForeColor = ConfigurationSettings.AppSettings["foreColor"];
            

            //textEditor.Styles[ScintillaNet.StylesCommon.Default
            newDocument.Width = newDocument.newDocWidth;
            newDocument.Height = newDocument.newDocHeight;


            newDocument.MdiParent = this;


            newDocument.Show();

            Documents.Add(newDocument);
            Documents[Documents.Count - 1].Text = "Document " + (Documents.Count - 1).ToString();
            return newDocument;
        }
        private Doc NewDoc(string s)
        {
            
            Doc n;

            if (s != "")
            {
                n = NewDoc();
                Scintilla te = new Scintilla();
                te = (Scintilla)n.Controls["textEditor"];
                StreamReader reader;
                try
                {
                    reader = new StreamReader(s);
                    te.Text = reader.ReadToEnd();
                    n.Text = s;
                    reader.Close();
                }
                catch
                {
                    MessageBox.Show("Error al leer archivo", "Error", MessageBoxButtons.OK);
                }

            }
            else
            {
                n = new Doc();
            }

            return n;
        }
        private void newFileMenuItem_Click(object sender, EventArgs e)
        {
            NewDoc();
        }

        private void exitMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        // ...
        private void saveFileMenuItem_Click(object sender, EventArgs e)
        {
            Scintilla txtEd = new Scintilla();
            txtEd = (Scintilla)ActiveMdiChild.Controls["textEditor"];

            if (ActiveMdiChild.Text.Substring(0, 8) == "Document")
            {
                saveFileDialog.Filter = fileDialogFilter;
                DialogResult dialogResult = saveFileDialog.ShowDialog();


                if (dialogResult == DialogResult.OK)
                {
                    StreamWriter save = new StreamWriter(saveFileDialog.FileName);
                    save.Write(txtEd.Text);
                    save.Close();
                    ActiveMdiChild.Text = saveFileDialog.FileName;
                }
            }
            else
            {
                StreamWriter save = new StreamWriter(ActiveMdiChild.Text);
                save.Write(txtEd.Text);
                save.Close();
            }
        }

        // ...
        private void closeFileMenuItem_Click(object sender, EventArgs e)
        {
            this.ActiveMdiChild.Close();
        }

        private void cascadeMenuItem_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(MdiLayout.Cascade);
        }

        private void tileHorizontalMenuItem_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void tileVerticalMenuItem_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(MdiLayout.TileVertical);
        }

        private void minimizeAllMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Doc d in Documents)
            {
                d.WindowState = FormWindowState.Minimized;
            }
        }

        private void openFileMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog.Filter = fileDialogFilter;
            openFileDialog.FileName = "";
            DialogResult dialogResult =  openFileDialog.ShowDialog();
           
            if (dialogResult == DialogResult.OK)
            {
                Doc newDocument = NewDoc(openFileDialog.FileName);
            }
        }

        private void saveAsMenuItem_Click(object sender, EventArgs e)
        {
            saveFileDialog.Filter = fileDialogFilter;
            DialogResult dialogResult = saveFileDialog.ShowDialog();

            RichTextBox txtEd = new RichTextBox();
            txtEd = (RichTextBox)ActiveMdiChild.Controls["textEditor"];
            if (dialogResult == DialogResult.OK)
            {
                StreamWriter save = new StreamWriter(saveFileDialog.FileName);
                save.Write(txtEd.Text);
                save.Close();
                ActiveMdiChild.Text = saveFileDialog.FileName;
            }
            
        }

        

    }
}

    //////////////////////////////
   




